<template>
  <div class="activity_detail">
    <div class="activityTitle">
      <div class="top_l">
        <h2 style="margin-right: 24px">{{ activityName }}</h2>
        <span>活动范围：</span>
        <div style="width: 300px; position: relative">
          <tree_select
            v-model="companyId"
            ref="areaTree"
            :treeList="companyList"
            selectPlaceholder="请选择"
            :maxTagCount="3"
            :saveParent="true"></tree_select>
        </div>
      </div>
      <div>
        <Button style="margin-right: 5px" type="primary" @click="closeCurrent">关闭</Button>
        <Button style="margin-right: 5px" type="primary" :disabled="statusLastFlag" @click="saveCurrent">
          保存
        </Button>
        <Button style="margin-right: 5px" type="primary" :disabled="statusLastFlag" @click="releaseCurrent">
          预览/发布
        </Button>
      </div>
    </div>

    <div class="bot_box">
      <div class="bothLeft">
        <div class="viewClass">预览：（保存后，即可在下方预览活动样式）</div>
        <div class="yeTit">
          <span
            v-for="(item, index) in yeTit"
            :key="item.id"
            class="title"
            :class="{ active: num == index }"
            @click="onGetIdx(index)">
            {{ item.name }}
          </span>
        </div>
        <div class="yeCon" id="v2ex">
          <div class="yeCOnTel" v-if="num == 2">
            <span>{{ acBasicsReq.phone }}</span>
            <img src="@/assets/images/prizeImg.png" />
          </div>
          <dt-iframe v-if="(num == 0 || num == 1) && imgFlag" :url="iframeUrl"></dt-iframe>
        </div>
      </div>
      <div class="setAll">
        <Tabs v-model="tabsBox" type="card" name="father">
          <TabPane label="基础设置" name="1" tab="father">
            <dt-info :label-width="150" ref="info1" :options="options1" style="width: 100%"></dt-info>
          </TabPane>
          <TabPane label="奖项设置" name="2" tab="father">
            <Tabs v-model="tabsChoose" :animated="false" type="card" @on-click="onClickTab" name="son">
              <TabPane
                :label="`奖品${index + 1}`"
                :name="String(index)"
                v-for="(item, index) in acPrizeReqList"
                :key="`${index}-${Math.random()}`"
                tab="son">
                <dt-info
                  :label-width="150"
                  ref="info2"
                  :info="item"
                  :options="options2[index]"
                  style="width: 100%"></dt-info>
              </TabPane>
              <div slot="extra">
                <Button @click="addPrize" type="primary" size="small" style="margin-right: 5px">
                  添加新奖品
                </Button>
                <Button @click="removePrize" size="small" type="primary">删除该奖品</Button>
              </div>
            </Tabs>
          </TabPane>
          <TabPane label="抽奖设置" name="3" tab="father">
            <dt-info :label-width="150" ref="info3" :options="options3" style="width: 100%"></dt-info>
          </TabPane>
          <TabPane label="任务配置" name="4" tab="father">
            <dt-info :label-width="150" ref="info4" :options="options4" style="width: 100%"></dt-info>
          </TabPane>
        </Tabs>
      </div>
    </div>

    <prize-publish ref="releaseModel" @publishUpdata="publishUpdata"></prize-publish>

    <img :src="base64Image" width="750" height="500" id="scream" style="display: none" />
    <canvas id="myCanvas" width="750" height="300" style="border: 1px solid #c3c3c3; display: none"></canvas>
    <preview-image
      :images="preViewImg"
      :showIndex="showIndex"
      :showDownLoad="true"
      ref="preViewImage"></preview-image>
  </div>
</template>

<script>
  import tree_select from '@/components/tree_select.vue'
  import toolMgr from '@/biz/base/tool'
  import editMgr from './opt/edit.js'
  import prizePublish from './components/prizePublish.vue'
  import activityMgr from '@/biz/activity/activity'
  import moment from 'moment'

  export default {
    data() {
      return {
        showIndex: 0,
        preViewImg: [],
        base64Image: '',
        acId: '', // 活动id
        activityName: '123',
        companyId: [],
        companyList: [],
        yeTit: [
          { id: 0, name: '封面页' },
          { id: 1, name: '活动页' },
          { id: 2, name: '中奖页' }
        ],
        num: 0,
        iframeUrl: '',
        imgFlag: false,
        tabsBox: '1',
        options1: null,
        options2: [],
        options3: null,
        options4: null,
        tabsChoose: '0',
        // 基础设置
        acBasicsReq: {
          accessoryBOList1: [], //活动封面图
          cover: '',
          accessoryBOList2: [], //顶部样式
          topStyle: '',
          accessoryBOList4: [], //图片展示
          projectShow: '',
          titleTag: '参与活动赢好礼', //页面标题
          activityTime: [],
          startDate: '',
          endDate: '',
          reason: null //活动说明
        },
        // 奖项设置
        acPrizeReqList: [
          {
            name: '奖品1',
            type: 1,
            accessoryBOList5: [],
            cover: '',
            unitPrice: null,
            count: 1,
            exchangeReason: '兑换方法及兑换地点说明',
            showPrize: [],
            interfaceEnable: false
          }
        ],
        // 抽奖设置
        acLotteryReq: {
          synthesisWinningRate: 10,
          initialLotteryCount: 1,
          winningCount: 1,
          everydayWinningCount: 100,
          winningLimitCount: 1,
          everyoneWinning: '0',
          everydayWinning: '0',
          winningLimit: '0'
        },
        // 任务配置
        taskOpt: {
          isHelp: false,
          taskAction: 'CLUE',
          shareCount: 1,
          limitCount: '0',
          shareLimitCount: 1
        },
        statusLastFlag: false
      }
    },
    watch: {
      num(val) {
        if (val == 0) {
          this.iframeUrl = `${this.$dt.env.h5Url}/#/pages/activity/index?acId=${this.acId}&from=2`
        } else {
          this.iframeUrl = `${this.$dt.env.h5Url}/#/pages/activity/detail?acId=${this.acId}&from=2&times=${this.acLotteryReq.initialLotteryCount}`
        }
      }
    },

    components: {
      tree_select,
      prizePublish
    },
    mounted() {
      this.acId = this.$route.query.acId
      this.iframeUrl = `${this.$dt.env.h5Url}/#/pages/activity/index?acId=${this.acId}&from=2`
      this.getDetail()
    },

    methods: {
      showModal() {
        this.preViewImg = ['https://static.tospurfang.com/dt-management/activity/manage_default.png']
        this.$refs.preViewImage.show()
      },
      publishUpdata(val) {
        console.log('子组件传值', val)
        this.getDetail()
      },
      getTreeData() {
        toolMgr.organization(2).then((res) => {
          this.companyList = res
          // if (this.$route.query) {
          //   this.activityName = this.$route.query.activityName
          //   this.companyId = [...this.$route.query.companyId.split(',')]
          // }
        })
      },
      closeCurrent() {
        this.$Modal.confirm({
          title: '关闭',
          content: '<p>如有修改未保存数据将丢失，是否离开当前页面？</p>',
          onOk: () => {
            this.$router.push({
              path: '/marketing/activity'
            })
          }
        })
      },
      // 保存
      async saveCurrent(rel) {
        return (
          (await this.check1()) &&
          (await this.check2()) &&
          (await this.check3()) &&
          (await this.check4()) &&
          this.updateActivity(rel)
        )
      },
      async releaseCurrent() {
        if (this.acBasicsReq.status == 'PUBLISHED') {
          this.$Modal.confirm({
            title: '提示',
            content: '<p>是否保存当前页面，保存后信息将同步到线上活动</p>',
            onOk: () => {
              this.saveCurrent('rel')
            }
          })
        } else {
          this.saveCurrent('rel')
        }
      },
      updateActivity(rel) {
        // alert(11)
        // return
        this.imgFlag = false
        this.dataProcess().then((res) => {
          activityMgr.updateBasics(res).then((res) => {
            if (rel === 'rel') {
              let dataVal = {
                acId: this.acId,
                status: this.acBasicsReq.status,
                times: this.acLotteryReq.initialLotteryCount
              }
              this.$refs.releaseModel.show(dataVal)
              this.options2 = []
              this.getDetail()
            } else {
              this.$Message.success('保存成功')
              this.options2 = []
              this.getDetail()
            }
          })
        })
      },
      check1() {
        return this.$refs.info1.validate().then((res) => {
          if (res) {
            return true
          } else {
            this.tabsBox = '1'
            return false
          }
        })
      },
      check2() {
        let countFlag = this.acPrizeReqList.some((item) => {
          return item.count > 0
        })
        if (!countFlag) {
          this.$Message.warning('至少有一个奖品的数量不为0')
          this.tabsBox = '2'
          return false
        } else {
          let arr = []
          this.$refs.info2.forEach((item, index) => {
            arr.push(item.validate())
          })
          return Promise.all(arr).then((res) => {
            if (res && res.length) {
              let _index = res.findIndex((item) => {
                return item === false
              })
              if (_index == -1) {
                return true
              } else {
                this.tabsBox = '2'
                this.tabsChoose = String(_index)
                setTimeout(() => {
                  this.$refs.info2[_index].validate().then((res) => {})
                }, 1000)
                return false
              }
            }
          })
        }
      },
      check3() {
        return this.$refs.info3.validate().then((res) => {
          if (res) {
            return true
          } else {
            this.tabsBox = '3'
            return false
          }
        })
      },
      check4() {
        return this.$refs.info4.validate().then((res) => {
          if (res) {
            return true
          } else {
            this.tabsBox = '4'
            return false
          }
        })
      },
      onGetIdx(index) {
        this.num = index
      },
      getDetail() {
        activityMgr.selectBasics({ acId: this.acId }).then((res) => {
          console.log('走到这里', res)
          if (res.acBasicsResp.status == 'END') {
            this.statusLastFlag = true
          } else if (res.acBasicsResp.status == 'PUBLISHED') {
            let endTime = moment(res.acBasicsResp.endDate, 'YYYY-MM-DD kk:mm:ss').format('x')
            let cuttentTime = moment().format('x')
            if (cuttentTime > endTime) {
              this.statusLastFlag = true
            } else {
              this.statusLastFlag = false
            }
          }

          this.acBasicsReq.status = res.acBasicsResp.status
          // 1基础格式化
          if (res && res.acBasicsResp) {
            this.activityName = res.acBasicsResp.name
            this.companyId =
              res.acBasicsResp.companyId && res.acBasicsResp.companyId.split(',').map((item) => Number(item))
            this.acBasicsReq = Object.assign(this.acBasicsReq, res.acBasicsResp)
          }
          if (res.acBasicsResp.startDate && res.acBasicsResp.endDate) {
            this.acBasicsReq.activityTime = [res.acBasicsResp.startDate, res.acBasicsResp.endDate]
          } else {
            this.acBasicsReq.activityTime = []
          }
          if (res.acBasicsResp.cover) {
            this.num = 0
            this.acBasicsReq.accessoryBOList1 = [
              {
                accessoryName: '',
                accessoryUrl: res.acBasicsResp.cover,
                name: '',
                url: res.acBasicsResp.cover
              }
            ]
          } else {
            this.num = 1
            this.acBasicsReq.accessoryBOList1 = []
          }
          if (res.acBasicsResp.topStyle) {
            this.acBasicsReq.accessoryBOList2 = [
              {
                accessoryName: '',
                accessoryUrl: res.acBasicsResp.topStyle,
                name: '',
                url: res.acBasicsResp.topStyle
              }
            ]
          } else {
            this.acBasicsReq.accessoryBOList2 = []
          }
          if (res.acBasicsResp.projectShow) {
            this.acBasicsReq.accessoryBOList4 = []
            let porSh = res.acBasicsResp.projectShow.split(',')
            porSh.forEach((item) => {
              this.acBasicsReq.accessoryBOList4.push({
                accessoryName: '',
                accessoryUrl: item,
                name: '',
                url: item
              })
            })
          } else {
            this.acBasicsReq.accessoryBOList4 = []
          }

          // 2奖项设置
          this.acPrizeReqList = []
          if (res && res.acPrizeRespList) {
            this.tabsChoose = '0'
            res.acPrizeRespList.forEach((item) => {
              console.log(111, item)
              if (item.type == 1) {
                item.unitPrice = null
              }
              item.showPrize = []
              if (item.cover) {
                item.accessoryBOList5 = [
                  {
                    accessoryName: '',
                    accessoryUrl: item.cover,
                    name: '',
                    url: item.cover
                  }
                ]
              } else {
                item.accessoryBOList5 = []
              }
              if (item.showInfo) {
                item.showPrize.push(1)
              }
              if (item.showAnonymous) {
                item.showPrize.push(2)
              }
              this.acPrizeReqList.push(item)
              if (item.type == 1) {
                this.options2.push(editMgr.options2(this))
              } else {
                this.options2.push(editMgr.options2(this, true))
              }
              console.log('options', this.options2)
            })
          }

          // 3抽奖设置格式化
          if (res && res.acLotteryResp) {
            this.acLotteryReq = res.acLotteryResp
            this.acLotteryReq.everyoneWinning = res.acLotteryResp.everyoneWinning ? '1' : '0'
            this.acLotteryReq.winningLimit = res.acLotteryResp.winningLimit ? '1' : '0'
            this.acLotteryReq.everydayWinning = res.acLotteryResp.everydayWinning ? '1' : '0'
          }

          // 4系统任务  type=3时为系统任务
          if (res && res.acHelpTaskRespList && res.acHelpTaskRespList[0]?.type == 3) {
            let systemTask = res.acHelpTaskRespList[0]
            this.taskOpt = Object.assign({}, systemTask)
            if (systemTask.shareLimit) {
              this.taskOpt.limitCount = '1'
            } else {
              this.taskOpt.limitCount = '0'
            }
          }

          this.options1 = editMgr.options1(this)
          this.$refs.info1.init(this.options1, this.acBasicsReq)
          // this.options2 = editMgr.options2(this)
          this.options3 = editMgr.options3(this)
          this.$refs.info3.init(this.options3, this.acLotteryReq)
          this.options4 = editMgr.options4(this)
          this.$refs.info4.init(this.options4, this.taskOpt)

          this.imgFlag = true
          this.getTreeData()
        })
      },
      dataProcess() {
        // 基础数据处理
        this.acBasicsReq.acId = this.acId
        this.acBasicsReq.companyIds = this.companyId
        this.acBasicsReq.cover = this.acBasicsReq.accessoryBOList1[0]
          ? this.acBasicsReq.accessoryBOList1[0].accessoryUrl
          : ''

        this.acBasicsReq.topStyle = this.acBasicsReq.accessoryBOList2[0]
          ? this.acBasicsReq.accessoryBOList2[0].accessoryUrl
          : ''

        let projectShow = []
        if (this.acBasicsReq.accessoryBOList4 && this.acBasicsReq.accessoryBOList4.length > 0) {
          this.acBasicsReq.accessoryBOList4.forEach((item) => {
            projectShow.push(item.accessoryUrl)
          })
          this.acBasicsReq.projectShow = projectShow.join(',')
        } else {
          this.acBasicsReq.projectShow = ''
        }
        this.acBasicsReq.startDate = this.acBasicsReq.activityTime[0] ? this.acBasicsReq.activityTime[0] : ''
        this.acBasicsReq.endDate = this.acBasicsReq.activityTime[1] ? this.acBasicsReq.activityTime[1] : ''
        // 奖品数据处理
        let acPrizeReqList = this.$tool.deepClone(this.acPrizeReqList)
        acPrizeReqList.forEach((item) => {
          item.cover = item.accessoryBOList5[0] ? item.accessoryBOList5[0].accessoryUrl : ''
          item.acId = this.acId
          if (item.showPrize.includes(1)) {
            item.showInfo = true
          } else {
            item.showInfo = false
          }
          if (item.showPrize.includes(2)) {
            item.showAnonymous = true
          } else {
            item.showAnonymous = false
          }
        })

        // 抽奖配置
        let acLotteryReq = Object.assign({}, this.acLotteryReq)
        if (acLotteryReq.everyoneWinning === '0') {
          acLotteryReq.everyoneWinning = false
        } else {
          acLotteryReq.everyoneWinning = true
        }

        if (acLotteryReq.winningLimit === '0') {
          acLotteryReq.winningLimit = false
        } else {
          acLotteryReq.winningLimit = true
        }

        if (acLotteryReq.everydayWinning === '0') {
          acLotteryReq.everydayWinning = false
        } else {
          acLotteryReq.everydayWinning = true
        }

        // 任务配置
        let acHelpTaskReqList = []
        this.taskOpt.acId = this.acId
        if (this.taskOpt.limitCount == '1') {
          this.taskOpt.shareLimit = true
        } else if (this.taskOpt.limitCount == '0') {
          this.taskOpt.shareLimit = false
        }
        acHelpTaskReqList.push(this.taskOpt)

        return new Promise((resolve, reject) => {
          let params = {
            acBasicsReq: this.acBasicsReq, //基础带活动id
            acPrizeReqList: acPrizeReqList,
            acLotteryReq: acLotteryReq,
            acHelpTaskReqList: acHelpTaskReqList
          }

          if (this.acBasicsReq.topStyle) {
            let img = document.getElementById('scream') //图片节点
            let c = document.getElementById('myCanvas') //canvas元素
            this.$dt.tool.getUrlBase64(this.acBasicsReq.topStyle).then((res) => {
              if (res) {
                this.base64Image = res
                setTimeout(() => {
                  this.$dt.tool.rgbafun(img, c).then((res) => {
                    params.acBasicsReq.backgroundColor = res
                    resolve(params)
                  })
                }, 0)
              }
            })
          } else {
            params.acBasicsReq.backgroundColor = null
            resolve(params)
          }
        })
      },
      onClickTab(val) {
        this.tabsChoose = String(val)
        // this.$set(this.options2, Number(val), editMgr.options2(this))
      },
      addPrize() {
        if (this.acPrizeReqList && this.acPrizeReqList.length < 7) {
          this.acPrizeReqList.push({
            name: '',
            type: 1,
            accessoryBOList5: [],
            cover: '',
            count: null,
            exchangeReason: '',
            showPrize: [],
            interfaceEnable: false,
            unitPrice: null
          })
          this.tabsChoose = this.acPrizeReqList && String(this.acPrizeReqList.length - 1)
          this.options2.push(editMgr.options2(this))
        } else {
          this.$Message.warning('最多添加7个奖品。')
        }
      },
      removePrize() {
        if (this.acPrizeReqList && this.acPrizeReqList.length < 2) {
          this.$Message.warning('至少保留一个奖品。')
        } else {
          this.$Modal.confirm({
            title: '删除',
            content: '你确认删除该奖品？',
            closable: true,
            onOk: () => {
              this.acPrizeReqList.splice(this.tabsChoose, 1)
              this.options2.splice(this.tabsChoose, 1)
              this.tabsChoose = '0'

              console.log('kankan', this.options2)
            }
          })
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .activityTitle {
    background-color: #f5f5f5;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
    padding: 0 14px 10px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    .top_l {
      display: flex;
      align-items: center;
    }
  }
  .bot_box {
    width: 100%;
    display: flex;
    .bothLeft {
      width: 400px;
      padding-left: 20px;
      .viewClass {
        padding: 10px 0 0 10px;
      }
      .yeTit {
        display: flex;
        flex-direction: row;
        width: 200px;
        span {
          cursor: pointer;
          padding: 5px 10px 10px 10px;
          line-height: 2;
        }
        span.active {
          color: #2d8cf0;
        }
      }
      .yeCon {
        width: 375px;
        height: 667px;
        .yeCOnTel {
          display: block;
          width: 100%;
          position: relative;
          padding: 12px;
          span {
            position: absolute;
            top: 432px;
            left: 122px;
            color: #000;
          }
        }
        img {
          display: block;
          width: 100%;
        }
      }
    }
  }
  .setAll {
    flex: 1;
    width: 100%;
    max-width: 800px;
    padding-left: 20px;
    padding-top: 20px;
    box-sizing: border-box;
  }
</style>
